package com.mallbook.model.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mallbook.model.exception.ServiceException;
import com.mallbook.model.pojo.Goods;
import com.mallbook.model.pojo.PageBean;
import com.mallbook.model.mapper.GoodsMapper;
import com.mallbook.model.utils.MallDefaultConfig;
import com.mallbook.model.utils.MybatisUtils;

import java.util.List;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-06-27
 * 商品数据页类
 */
public class PageBeanGoods {
    /**
     * @param goods 条件
     * @param page  页数
     * @return
     */
    public static PageBean<Goods> getByPage(Goods goods, int page) {
        GoodsMapper goodsMapper = MybatisUtils.getMappers(GoodsMapper.class);
        int pageSize = MallDefaultConfig.GOODS_PAGE_SIZE;
        // 根据条件，页码，分页大小，将PageBean中的属性依次设置
        PageBean<Goods> pageBean = new PageBean<>();
        Page p = PageHelper.startPage(page, pageSize);
        List<Goods> data = null;
        if (goods == null) {
            try {
                // 查询所有商品
                data = goodsMapper.findGoods();
            } catch (
                    ServiceException e) {
                e.printStackTrace();
                System.out.println("系统维护中");
            }
        } else {
            try {
                // 条件查询
                data = goodsMapper.findGoodsByCondition(goods);
            } catch (
                    ServiceException e) {
                e.printStackTrace();
                System.out.println("系统维护中");
            }
        }
        pageBean.setData(data);
        pageBean.setCurrPage(page);
        pageBean.setCurrPageSize(data.size());
        pageBean.setPageSize(pageSize);
        pageBean.setTotalNums((int) p.getTotal());
        pageBean.setTotalPages(p.getPages());

        return pageBean;
    }
}
